<script setup lang="ts">
import { ref } from "vue";
import { Delete, Promotion } from "@element-plus/icons-vue";
import { ElButton, ElInput, ElMessage } from "element-plus";
import { ProForm, ProInputNumber, ProRadioGroup } from "@/modules/package/form";

import ApiActivity from "@/api/activity";
import useEnum from "@/hooks/useEnum";
import useForm from "@/hooks/useForm";
import { TSpec } from "@/types/global";

const { source, modalApi } = defineProps<{
  source?: TSpec;
  modalApi?: any;
}>();

const emits = defineEmits<{
  success: [];
}>();

const { list: listStatus } = useEnum("EnumStatus");
const { list: listIsTime } = useEnum("EnumSpecIsTime");

// 表单项
const formItems = [
  {
    label: "规格名称",
    children: {
      type: ElInput,
      field: "spec_name",
    },
  },
  {
    label: "是否时间格式",
    children: {
      type: ProRadioGroup,
      field: "is_date",
      props: {
        options: listIsTime,
      },
    },
  },
  {
    label: "规格状态",
    children: {
      type: ProRadioGroup,
      field: "status",
      props: {
        options: listStatus,
      },
    },
  },
  {
    label: "排序",
    children: {
      type: ProInputNumber,
      field: "sort",
      props: {
        min: 1,
        max: 9999,
        precision: 0,
      },
    },
  },
  {
    label: "备注",
    children: {
      type: ElInput,
      field: "remark",
      props: {
        type: "textarea",
      },
    },
  },
  {
    label: "规格内容",
    slot: "spec_value",
    prop: "spec_value",
    children: {
      field: "spec_value",
    },
  },
];

const { refForm, isFetching, model, submit, reset, onFetchResponse } = useForm<
  Omit<TSpec, "spec_value"> & { spec_value: string[] }
>(source ? ApiActivity.specEdit : ApiActivity.specAdd, {
  defaultModel: Object.assign(
    {
      status: 1,
      is_date: 2,
      spec_value: [],
    },
    source && {
      ...source,
      spec_value: source.spec_value?.split(";").map(decodeURIComponent) || [],
    }
  ),
  formatModel(data) {
    return {
      ...data,
      spec_value: data.spec_value.map(encodeURIComponent).join(";"),
    };
  },
});

onFetchResponse(() => {
  ElMessage.success("操作成功！");
  modalApi?.close();
  emits("success");
});

const specVal = ref<string>("");

// 添加规格内容
const confirmSpecVal = () => {
  const val = specVal.value.trim();
  if (val) model.value.spec_value.push(val);

  specVal.value = "";
};

// 移除规格内容
const removeSpec = (index: number) => {
  model.value.spec_value.splice(index, 1);
};

// 表单验证：规格内容
const validator = (_: any, value: string[], callback: any) => {
  const index = value.findIndex((e: string) => !e.trim());

  if (value.length == 0) {
    callback(new Error(`请输入规格内容`));
  } else if (index > -1) {
    callback(new Error(`第${index}项规格不可为空,请补充`));
  } else {
    callback();
  }
};
const rules = {
  sort: { required: true, message: "请输入排序值" },
  spec_name: { required: true, message: "请输入规格名称" },
  spec_value: { required: true, validator, message: "请补充规格内容" },
};
</script>

<template>
  <ProForm
    ref="refForm"
    :form-items="formItems"
    :model="model"
    :col="24"
    :rules="rules"
    label-width="8em"
    :loading="isFetching"
    @reset="reset"
    @submit="submit"
  >
    <template #spec_value>
      <template v-for="(item, index) in model.spec_value">
        <div class="flex w-full mb-3">
          <ElInput
            v-model="model.spec_value[index]"
            class="flex-auto"
            placeholder="输入规格"
          />
          <div class="flex-none ml-3">
            <ElButton
              :icon="Delete"
              circle
              type="danger"
              @click="removeSpec(index)"
            />
          </div>
        </div>
      </template>

      <div class="flex w-full">
        <ElInput
          v-model="specVal"
          class="flex-auto"
          placeholder="输入规格(可按Enter键确认)"
          @keyup.enter="confirmSpecVal"
        />
        <div class="flex-none ml-3">
          <ElButton
            :icon="Promotion"
            circle
            type="primary"
            @click="confirmSpecVal"
          />
        </div>
      </div>
    </template>
  </ProForm>
</template>
